"""
日志工具类 - 处理Windows特有的日志问题
"""

import os
import sys
import time
import threading
from pathlib import Path
from typing import Optional
from loguru import logger as loguru_logger


class SafeLogHandler:
    """安全的日志处理器，解决Windows文件锁定问题"""
    
    def __init__(self, log_file: str, max_retries: int = 3, retry_delay: float = 0.1):
        self.log_file = Path(log_file)
        self.max_retries = max_retries
        self.retry_delay = retry_delay
        self._lock = threading.Lock()
        
    def ensure_log_directory(self) -> bool:
        """确保日志目录存在"""
        try:
            self.log_file.parent.mkdir(parents=True, exist_ok=True)
            return True
        except Exception as e:
            print(f"创建日志目录失败: {e}")
            return False
    
    def check_file_permissions(self) -> bool:
        """检查文件权限"""
        try:
            if self.log_file.exists():
                # 检查文件是否可写
                with open(self.log_file, 'a', encoding='utf-8') as f:
                    pass
                return True
            else:
                # 检查目录是否可写
                test_file = self.log_file.parent / 'test_write.tmp'
                with open(test_file, 'w', encoding='utf-8') as f:
                    f.write('test')
                test_file.unlink()
                return True
        except Exception as e:
            print(f"文件权限检查失败: {e}")
            return False
    
    def get_safe_log_config(self) -> dict:
        """获取安全的日志配置"""
        config = {
            'format': "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
            'level': "INFO",
            'rotation': "10 MB",
            'retention': "30 days",
            'compression': "zip",
            'enqueue': True,  # 使用队列避免多进程冲突
            'serialize': False,
            'backtrace': True,
            'diagnose': True,
            'buffering': 1,  # 行缓冲
            'encoding': "utf-8",
            'delay': True,  # 延迟创建文件
        }
        
        # Windows特定优化
        if sys.platform.startswith('win'):
            config.update({
                'catch': True,  # 捕获异常
                'colorize': False,  # 文件输出不使用颜色
            })
        
        return config


def setup_safe_logger(log_file: str, log_level: str = "INFO") -> bool:
    """设置安全的日志系统"""
    handler = SafeLogHandler(log_file)
    
    # 确保日志目录存在
    if not handler.ensure_log_directory():
        return False
    
    # 检查文件权限
    if not handler.check_file_permissions():
        print(f"警告：日志文件权限不足，将仅使用控制台输出")
        return False
    
    try:
        # 获取安全配置
        config = handler.get_safe_log_config()
        config['level'] = log_level
        
        # 添加文件处理器
        loguru_logger.add(log_file, **config)
        
        # 测试写入
        loguru_logger.info("日志系统初始化成功")
        return True
        
    except Exception as e:
        print(f"日志系统初始化失败: {e}")
        return False


def cleanup_old_logs(log_dir: str, max_age_days: int = 30):
    """清理旧的日志文件"""
    try:
        log_path = Path(log_dir)
        if not log_path.exists():
            return
        
        current_time = time.time()
        max_age_seconds = max_age_days * 24 * 3600
        
        for log_file in log_path.glob("*.log*"):
            try:
                file_age = current_time - log_file.stat().st_mtime
                if file_age > max_age_seconds:
                    log_file.unlink()
                    print(f"清理旧日志文件: {log_file}")
            except Exception as e:
                print(f"清理日志文件失败 {log_file}: {e}")
                
    except Exception as e:
        print(f"日志清理过程失败: {e}")


def get_log_file_info(log_file: str) -> dict:
    """获取日志文件信息"""
    try:
        log_path = Path(log_file)
        if not log_path.exists():
            return {'exists': False}
        
        stat = log_path.stat()
        return {
            'exists': True,
            'size': stat.st_size,
            'size_mb': round(stat.st_size / (1024 * 1024), 2),
            'modified': time.ctime(stat.st_mtime),
            'readable': os.access(log_path, os.R_OK),
            'writable': os.access(log_path, os.W_OK),
        }
    except Exception as e:
        return {'exists': False, 'error': str(e)}
